const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config({ path: '../.env' }); // 假设 .env 文件在项目根目录

// 导入所有模型
const Admin = require('../src/models/admin.model');
const User = require('../src/models/user.model');
const Food = require('../src/models/food.model');
const FoodCategory = require('../src/models/foodCategory.model');
const Recipe = require('../src/models/recipe.model');
const RecipeCategory = require('../src/models/recipeCategory.model');
const DietRecord = require('../src/models/dietRecord.model');
const NutritionGoal = require('../src/models/nutritionGoal.model');
const NutritionSuggestion = require('../src/models/nutritionSuggestion.model');
const SearchHistory = require('../src/models/searchHistory.model');
const Tag = require('../src/models/tag.model');
const Role = require('../src/models/role.model');
const SystemSetting = require('../src/models/systemSetting.model');
const NotificationSetting = require('../src/models/notificationSetting.model');
const BackupSetting = require('../src/models/backupSetting.model');
const Backup = require('../src/models/backup.model');
const UserActivityLog = require('../src/models/userActivityLog.model');
// const Token = require('../src/models/token.model'); // Token 通常由系统生成，可能不需要手动填充

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/health-app-dev';

// --- 占位符数据 ---
const placeholderImages = {
    avatar: [
        'https://images.unsplash.com/photo-1535713875002-d1d0cf377fDE?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60',
        'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60',
        'https://images.unsplash.com/photo-1527980965255-d3b416303d12?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60',
    ],
    food: [
        'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', // General food
        'https://images.unsplash.com/photo-1484723091739-30a097e8f929?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', // Breakfast
        'https://images.unsplash.com/photo-1504674900247-0877df9cc836?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', // Lunch/Dinner
        'https://images.unsplash.com/photo-1497034825429-c343d7c6a68f?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', // Fruits
        'https://images.unsplash.com/photo-1551248529-3d9090535058?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', // Vegetables
    ],
    recipeCover: [
        'https://images.unsplash.com/photo-1476224203421-9ac39bcb3327?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80',
        'https://images.unsplash.com/photo-1414235077428-338989a2e8c0?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80',
        'https://images.unsplash.com/photo-1482049016688-2d3e1b311543?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80',
    ],
    recipeStep: [
        'https://images.unsplash.com/photo-1506368249639-73a05d6f6488?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=60',
        'https://images.unsplash.com/photo-1580959375944-abd7cec60112?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=60',
    ],
    categoryIcons: [ // Font Awesome or Bootstrap Icons classes
        'fas fa-utensils', 'bi bi-egg-fried', // Food related
        'fas fa-apple-alt', 'bi bi-basket',   // Fruits/Vegetables
        'fas fa-carrot', 'bi bi-flower1',
        'fas fa-drumstick-bite', 'bi bi-egg',
        'fas fa-bread-slice', 'bi bi-graph-up', // Generic
        'fas fa-cogs', 'bi bi-gear-fill',       // Settings
        'fas fa-bell', 'bi bi-bell-fill',       // Notifications
        'fas fa-save', 'bi bi-cloud-download-fill', // Backup
        'fas fa-users', 'bi bi-people-fill',     // Users/Roles
        'fas fa-tags', 'bi bi-tags-fill',       // Tags
        'fas fa-book-open', 'bi bi-journal-richtext' // Recipes
    ]
};

const getRandomItem = (arr) => arr[Math.floor(Math.random() * arr.length)];
const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const getRandomDate = (start, end) => new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));

async function connectDB() {
    try {
        await mongoose.connect(MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            // useCreateIndex: true, // Mongoose 6 no longer supports these options
            // useFindAndModify: false,
        });
        console.log('MongoDB Connected...');
    } catch (err) {
        console.error('MongoDB connection error:', err.message);
        process.exit(1);
    }
}

async function clearDatabase() {
    console.log('Clearing database...');
    const collections = mongoose.connection.collections;
    for (const key in collections) {
        const collection = collections[key];
        try {
            await collection.deleteMany({});
            console.log(`Cleared ${key} collection.`);
        } catch (error) {
            // Handle specific errors, e.g., if a collection doesn't exist or cannot be dropped
            if (error.message.includes('ns not found')) {
                console.warn(`Collection ${key} not found, skipping clear.`);
            } else {
                console.error(`Error clearing collection ${key}:`, error.message);
            }
        }
    }
    console.log('Database cleared.');
}


// --- Admin Data ---
async function seedAdmins() {
    try {
        const adminData = [
            {
                username: 'admin',
                password: 'admin123', // Will be hashed
                name: '超级管理员',
                role: '超级管理员',
                permissions: ['manageUsers', 'manageContent', 'manageSystem', 'all'],
                avatar: getRandomItem(placeholderImages.avatar),
                isActive: true,
            },
            {
                username: 'editor',
                password: 'editor123',
                name: '内容管理员',
                role: '内容管理员',
                permissions: ['manageContent'],
                avatar: getRandomItem(placeholderImages.avatar),
                isActive: true,
            }
        ];

        // Hash passwords
        // for (let admin of adminData) { // This was correctly commented out earlier
        //     if (admin.password) { 
        //         // admin.password = await bcrypt.hash(admin.password, 8); // Hashing is handled by pre-save hook in model if .save() is called
        //     }
        // }
        
        // await Admin.insertMany(adminData); // insertMany does not trigger 'save' hooks
        await Admin.create(adminData); // .create() will trigger 'save' hooks for each document
        console.log('Admin data seeded.');
        return await Admin.find();
    } catch (error) {
        console.error('Error seeding admins:', error);
        throw error;
    }
}

// --- User Data ---
async function seedUsers() {
    try {
        const usersData = [];
        const goals = ['减脂', '增肌', '健康饮食'];
        for (let i = 0; i < 50; i++) {
            usersData.push({
                name: `用户${i + 1}`,
                nickname: `小用户${i + 1}`,
                avatar: getRandomItem(placeholderImages.avatar),
                email: `user${i + 1}@example.com`,
                password: `password${i + 1}`, // Will be hashed by model pre-save hook
                wechatOpenid: `openid_user_${i + 1}_${Date.now()}`,
                role: 'user',
                isEmailVerified: Math.random() < 0.7,
                gender: getRandomNumber(0, 2),
                height: getRandomNumber(150, 190),
                weight: getRandomNumber(45, 100),
                age: getRandomNumber(18, 60),
                activityLevel: getRandomNumber(1, 5),
                goal: getRandomItem(goals),
                dailyCalorieGoal: getRandomNumber(1500, 3000),
                lastLoginAt: getRandomDate(new Date(2023, 0, 1), new Date()),
                isActive: Math.random() < 0.9,
            });
        }
        await User.insertMany(usersData);
        console.log('User data seeded.');
        return await User.find();
    } catch (error) {
        console.error('Error seeding users:', error);
        throw error;
    }
}

// --- FoodCategory Data ---
async function seedFoodCategories() {
    try {
        const categories = [
            { name: '水果', icon: getRandomItem(placeholderImages.categoryIcons), description: '新鲜水果类食物', order: 1, isActive: true },
            { name: '蔬菜', icon: getRandomItem(placeholderImages.categoryIcons), description: '各类蔬菜食材', order: 2, isActive: true },
            { name: '谷物', icon: getRandomItem(placeholderImages.categoryIcons), description: '主食和谷物类', order: 3, isActive: true },
            { name: '肉类', icon: getRandomItem(placeholderImages.categoryIcons), description: '各种肉类', order: 4, isActive: true },
            { name: '乳制品', icon: getRandomItem(placeholderImages.categoryIcons), description: '牛奶、酸奶、奶酪等', order: 5, isActive: true },
            { name: '豆制品', icon: getRandomItem(placeholderImages.categoryIcons), description: '豆腐、豆浆等', order: 6, isActive: true },
            { name: '坚果与种子', icon: getRandomItem(placeholderImages.categoryIcons), description: '各种坚果和种子', order: 7, isActive: true },
            { name: '饮品', icon: getRandomItem(placeholderImages.categoryIcons), description: '水、茶、咖啡等（不含酒精）', order: 8, isActive: true },
            { name: '零食', icon: getRandomItem(placeholderImages.categoryIcons), description: '健康的零食选择', order: 9, isActive: false },
            { name: '调味品', icon: getRandomItem(placeholderImages.categoryIcons), description: '盐、糖、酱油等', order: 10, isActive: true },
        ];
        await FoodCategory.insertMany(categories);
        console.log('FoodCategory data seeded.');
        return await FoodCategory.find();
    } catch (error) {
        console.error('Error seeding food categories:', error);
        throw error;
    }
}

// --- Food Data ---
async function seedFoods(foodCategories) {
    if (!foodCategories || foodCategories.length === 0) {
        console.error('Cannot seed foods without food categories.');
        return [];
    }
    try {
        const foodsData = [];
        const foodNames = ['苹果', '香蕉', '橙子', '草莓', '蓝莓', '西兰花', '胡萝卜', '菠菜', '鸡胸肉', '牛肉', '三文鱼', '鸡蛋', '牛奶', '酸奶', '全麦面包', '糙米', '燕麦片', '杏仁', '核桃', '豆腐'];
        
        for (let i = 0; i < 200; i++) {
            const randomCategory = getRandomItem(foodCategories);
            foodsData.push({
                name: `${getRandomItem(foodNames)} ${i % 5 === 0 ? '(有机)' : ''}`.trim(),
                categoryId: randomCategory._id,
                image: getRandomItem(placeholderImages.food),
                unit: '克',
                calories: getRandomNumber(30, 500), // 每100克
                nutrition: {
                    protein: getRandomNumber(0, 30),
                    fat: getRandomNumber(0, 20),
                    carbohydrate: getRandomNumber(0, 70),
                    fiber: getRandomNumber(0, 15),
                    sugar: getRandomNumber(0, 50),
                    sodium: getRandomNumber(0, 500),
                    cholesterol: getRandomNumber(0, 100),
                    vitamins: { A: getRandomNumber(0,100), C: getRandomNumber(0,100), D: getRandomNumber(0,100)},
                    minerals: { calcium: getRandomNumber(0,200), iron: getRandomNumber(0,10)}
                },
                isVerified: Math.random() < 0.8,
                source: Math.random() < 0.5 ? '用户贡献' : '中国食物成分表',
            });
        }
        await Food.insertMany(foodsData);
        console.log('Food data seeded.');
        return await Food.find();
    } catch (error) {
        console.error('Error seeding foods:', error);
        throw error;
    }
}


// --- RecipeCategory Data ---
async function seedRecipeCategories() {
    try {
        const categories = [
            { name: '家常菜', icon: getRandomItem(placeholderImages.categoryIcons), description: '日常家庭烹饪的菜肴', order: 1, isActive: true },
            { name: '快手菜', icon: getRandomItem(placeholderImages.categoryIcons), description: '制作简单快捷的菜肴', order: 2, isActive: true },
            { name: '减肥餐', icon: getRandomItem(placeholderImages.categoryIcons), description: '适合减肥期间食用的健康餐', order: 3, isActive: true },
            { name: '健身餐', icon: getRandomItem(placeholderImages.categoryIcons), description: '高蛋白、低脂肪的健身食谱', order: 4, isActive: true },
            { name: '汤羹', icon: getRandomItem(placeholderImages.categoryIcons), description: '各种营养汤品和羹类', order: 5, isActive: true },
            { name: '烘焙', icon: getRandomItem(placeholderImages.categoryIcons), description: '面包、蛋糕等烘焙点心', order: 6, isActive: false },
            { name: '饮品', icon: getRandomItem(placeholderImages.categoryIcons), description: '自制健康饮品', order: 7, isActive: true },
            { name: '宝宝辅食', icon: getRandomItem(placeholderImages.categoryIcons), description: '适合婴幼儿的辅食', order: 8, isActive: true },
        ];
        await RecipeCategory.insertMany(categories);
        console.log('RecipeCategory data seeded.');
        return await RecipeCategory.find();
    } catch (error) {
        console.error('Error seeding recipe categories:', error);
        throw error;
    }
}


// --- Recipe Data ---
async function seedRecipes(recipeCategories, foods, admins) {
    if (!recipeCategories || recipeCategories.length === 0) {
        console.error('Cannot seed recipes without recipe categories.'); return [];
    }
    if (!foods || foods.length === 0) {
        console.error('Cannot seed recipes without foods.'); return [];
    }
    if (!admins || admins.length === 0) {
        console.error('Cannot seed recipes without admin authors.'); return [];
    }

    try {
        const recipesData = [];
        const recipeTitles = ['美味鸡胸肉沙拉', '快手番茄炒蛋', '香煎三文鱼配芦笋', '营养燕麦粥', '红烧牛肉面', '蒜蓉西兰花', '豆腐金针菇汤', '蓝莓香蕉思慕雪'];
        const units = ['克', '毫升', '个', '块', '勺', '杯'];

        for (let i = 0; i < 50; i++) {
            const randomCategory = getRandomItem(recipeCategories);
            const randomAdmin = getRandomItem(admins);
            const numIngredients = getRandomNumber(2, 5);
            const ingredients = [];
            for(let j=0; j<numIngredients; j++) {
                const randomFood = getRandomItem(foods);
                ingredients.push({
                    food: { _id: randomFood._id, name: randomFood.name },
                    amount: getRandomNumber(50, 300),
                    unit: getRandomItem(units)
                });
            }

            const numSteps = getRandomNumber(3, 7);
            const steps = [];
            for(let k=0; k<numSteps; k++) {
                steps.push({
                    description: `步骤 ${k+1}：这是第 ${k+1} 个烹饪步骤的详细描述...`,
                    image: Math.random() < 0.5 ? getRandomItem(placeholderImages.recipeStep) : null,
                    duration: getRandomNumber(5, 30)
                });
            }
            
            recipesData.push({
                title: `${getRandomItem(recipeTitles)} - ${i + 1}`,
                description: `这是一道美味又健康的${randomCategory.name}食谱，简单易学，适合${randomAdmin.name}推荐。`,
                coverImage: getRandomItem(placeholderImages.recipeCover),
                category: { _id: randomCategory._id, name: randomCategory.name },
                difficulty: getRandomNumber(1, 5),
                prepTime: getRandomNumber(10, 30),
                cookTime: getRandomNumber(15, 60),
                servings: getRandomNumber(1, 4),
                ingredients: ingredients,
                steps: steps,
                tips: ['小贴士1：xxx', '小贴士2：yyy'],
                nutrition: {
                    calories: getRandomNumber(200, 800),
                    protein: getRandomNumber(10, 50),
                    fat: getRandomNumber(5, 40),
                    carbohydrates: getRandomNumber(20, 100),
                },
                tags: [getRandomItem(['健康', '快手', '美味', '低脂', '高蛋白']), randomCategory.name],
                author: { _id: randomAdmin._id, name: randomAdmin.name, username: randomAdmin.username },
                isVerified: Math.random() < 0.9,
                viewCount: getRandomNumber(100, 5000),
                likeCount: getRandomNumber(10, 1000),
                favoriteCount: getRandomNumber(5, 500),
            });
        }
        await Recipe.insertMany(recipesData);
        console.log('Recipe data seeded.');
        return await Recipe.find();
    } catch (error) {
        console.error('Error seeding recipes:', error);
        throw error;
    }
}

// --- DietRecord Data ---
async function seedDietRecords(users, foods) {
    if (!users || users.length === 0) { console.error('No users to seed diet records for.'); return []; }
    if (!foods || foods.length === 0) { console.error('No foods to seed in diet records.'); return []; }

    try {
        const dietRecordsData = [];
        const mealTypes = ['早餐', '午餐', '晚餐', '加餐'];

        for (const user of users) {
            for (let i = 0; i < getRandomNumber(10, 30); i++) {
                const recordDate = getRandomDate(new Date(2023, 10, 1), new Date());
                const recordTime = `${String(getRandomNumber(7, 22)).padStart(2, '0')}:${String(getRandomNumber(0, 59)).padStart(2, '0')}`;
                
                const numFoodsInRecord = getRandomNumber(1, 4);
                const recordFoods = [];
                let totalCalories = 0;
                const totalNutrition = { protein: 0, fat: 0, carbohydrate: 0 };

                for (let j = 0; j < numFoodsInRecord; j++) {
                    const randomFood = getRandomItem(foods);
                    const amount = getRandomNumber(50, 200);
                    const foodCalories = Math.round((randomFood.calories / 100) * amount);
                    const foodProtein = Math.round((randomFood.nutrition.protein / 100) * amount);
                    const foodFat = Math.round((randomFood.nutrition.fat / 100) * amount);
                    const foodCarbs = Math.round((randomFood.nutrition.carbohydrate / 100) * amount);
                    
                    recordFoods.push({
                        food: { _id: randomFood._id, name: randomFood.name, image: randomFood.image, unit: randomFood.unit, calories: randomFood.calories },
                        amount: amount,
                        unit: '克',
                        calories: foodCalories,
                        nutrition: { protein: foodProtein, fat: foodFat, carbohydrate: foodCarbs }
                    });
                    totalCalories += foodCalories;
                    totalNutrition.protein += foodProtein;
                    totalNutrition.fat += foodFat;
                    totalNutrition.carbohydrate += foodCarbs;
                }

                dietRecordsData.push({
                    userId: user._id,
                    mealType: getRandomItem(mealTypes),
                    date: recordDate,
                    time: recordTime,
                    foods: recordFoods,
                    note: Math.random() < 0.3 ? `今天吃了很健康的${getRandomItem(mealTypes)}` : '',
                    images: Math.random() < 0.1 ? [getRandomItem(placeholderImages.food)] : [],
                    totalCalories: totalCalories,
                    totalNutrition: totalNutrition,
                });
            }
        }
        await DietRecord.insertMany(dietRecordsData);
        console.log('DietRecord data seeded.');
        return await DietRecord.find();
    } catch (error) {
        console.error('Error seeding diet records:', error);
        throw error;
    }
}

// --- NutritionGoal Data ---
async function seedNutritionGoals(users) {
    if (!users || users.length === 0) { console.error('No users to seed nutrition goals for.'); return []; }
    try {
        const goalsData = [];
        for (const user of users) {
            if (Math.random() < 0.8) {
                const caloriesGoal = user.dailyCalorieGoal || getRandomNumber(1800, 2800);
                goalsData.push({
                    userId: user._id,
                    caloriesGoal: caloriesGoal,
                    nutritionGoals: {
                        protein: Math.round(caloriesGoal * 0.20 / 4),
                        fat: Math.round(caloriesGoal * 0.30 / 9),
                        carbohydrate: Math.round(caloriesGoal * 0.50 / 4),
                        fiber: getRandomNumber(25, 35),
                        sugar: getRandomNumber(30, 60),
                        sodium: getRandomNumber(1500, 2300)
                    },
                    macroRatio: {
                        protein: 20,
                        fat: 30,
                        carbohydrate: 50
                    }
                });
            }
        }
        await NutritionGoal.insertMany(goalsData);
        console.log('NutritionGoal data seeded.');
        return await NutritionGoal.find();
    } catch (error) {
        console.error('Error seeding nutrition goals:', error);
        throw error;
    }
}

// --- NutritionSuggestion Data (Example) ---
async function seedNutritionSuggestions(users, foods) {
    if (!users || users.length === 0) { console.error('No users for suggestions.'); return []; }
    if (!foods || foods.length === 0) { console.error('No foods for suggestions.'); return []; }
    try {
        const suggestionsData = [];
        const suggestionTypes = ['营养均衡', '热量控制', '蛋白质补充', '膳食纤维'];
        
        for (const user of users) {
            if (Math.random() < 0.7) {
                 const foodSuggest = [];
                 for(let k=0; k < getRandomNumber(2,5); k++){
                    const randomFoodSugg = getRandomItem(foods);
                    foodSuggest.push({
                        food: { _id: randomFoodSugg._id, name: randomFoodSugg.name, image: randomFoodSugg.image },
                        reason: "富含优质营养素，适合您当前目标"
                    });
                 }

                suggestionsData.push({
                    userId: user._id,
                    type: getRandomItem(suggestionTypes),
                    content: `根据您近期的饮食记录，我们建议您关注 ${getRandomItem(['蛋白质', '膳食纤维', '维生素C'])} 的摄入。`,
                    detail: `详细分析表明，您在 ${getRandomItem(['蛋白质', '膳食纤维', '维生素C'])} 方面的摄入量可以进一步优化，以更好地达成您的健康目标。例如，可以多吃一些...`,
                    foodSuggestions: foodSuggest,
                    baseData: {
                        period: "week",
                        startDate: "2023-11-01",
                        endDate: "2023-11-07",
                        averageProtein: getRandomNumber(40, 80),
                        recommendedProtein: getRandomNumber(70, 120)
                    },
                    isRead: Math.random() < 0.3
                });
            }
        }
        await NutritionSuggestion.insertMany(suggestionsData);
        console.log('NutritionSuggestion data seeded.');
        return await NutritionSuggestion.find();
    } catch (error) {
        console.error('Error seeding nutrition suggestions:', error);
        throw error;
    }
}


// --- Tag Data ---
async function seedTags() {
    try {
        const tags = [
            { name: '低热量', description: '低热量食物和食谱', count: getRandomNumber(10,50) },
            { name: '高蛋白', description: '高蛋白食物和食谱', count: getRandomNumber(10,50) },
            { name: '素食', description: '适合素食者的食物和食谱', count: getRandomNumber(5,30) },
            { name: '无麸质', description: '不含麸质的食物和食谱', count: getRandomNumber(5,20) },
            { name: '早餐', description: '适合早餐的食谱', count: getRandomNumber(10,40) },
            { name: '午餐', description: '适合午餐的食谱', count: getRandomNumber(10,40) },
            { name: '晚餐', description: '适合晚餐的食谱', count: getRandomNumber(10,40) },
            { name: '健身', description: '适合健身人士的食谱', count: getRandomNumber(10,30) },
        ];
        await Tag.insertMany(tags);
        console.log('Tag data seeded.');
        return await Tag.find();
    } catch (error) {
        console.error('Error seeding tags:', error);
        throw error;
    }
}

// --- Role Data ---
async function seedRoles() {
    try {
        const roles = [
            { 
                name: '超级管理员', 
                description: '拥有所有系统权限', 
                permissions: [{ module: "all", actions: ["all"] }]
            },
            { 
                name: '内容管理员', 
                description: '管理食物、食谱等内容', 
                permissions: [
                    { module: "food", actions: ["view", "add", "edit", "delete"] },
                    { module: "recipe", actions: ["view", "add", "edit", "delete"] },
                    { module: "foodCategory", actions: ["view", "add", "edit", "delete"] },
                    { module: "recipeCategory", actions: ["view", "add", "edit", "delete"] }
                ]
            },
            { 
                name: '用户管理员', 
                description: '管理用户信息和权限', 
                permissions: [
                    { module: "user", actions: ["view", "edit", "delete"] },
                    { module: "role", actions: ["view"] }
                ]
            },
            { 
                name: '普通用户', 
                description: '小程序普通用户', 
                permissions: [
                    { module: "food", actions: ["view"] },
                    { module: "recipe", actions: ["view"] },
                    { module: "dietRecord", actions: ["view", "add", "edit", "deleteSelf"] },
                ]
            }
        ];
        await Role.insertMany(roles);
        console.log('Role data seeded.');
        return await Role.find();
    } catch (error) {
        console.error('Error seeding roles:', error);
        throw error;
    }
}


// --- SystemSetting Data ---
async function seedSystemSettings() {
    try {
        const systemSettingData = {
            systemName: '健康饮食助手管理后台',
            systemVersion: '1.0.0',
            adminEmail: 'admin@example.com',
            contactPhone: '13800138000',
            cacheTime: 30,
            pageSize: 20,
            defaultLanguage: 'zh-CN',
            timezone: 'Asia/Shanghai',
            features: {
                userRegistration: true,
                userRecipeCreation: false,
                autoNutritionAnalysis: true,
                userFoodContribution: true,
                maintenanceMode: false,
            }
        };
        await SystemSetting.create(systemSettingData);
        console.log('SystemSetting data seeded.');
        return await SystemSetting.findOne();
    } catch (error) {
        console.error('Error seeding system settings:', error);
        throw error;
    }
}

// --- NotificationSetting Data ---
async function seedNotificationSettings() {
    try {
        const notificationSettingData = {
            systemNotifications: {
                systemUpdate: true,
                securityAlert: true,
                backupResult: true,
            },
            businessNotifications: {
                newUserRegistration: true,
                foodSubmission: true,
                recipePublication: false,
                userFeedback: true,
            },
            notificationMethods: {
                inApp: true,
                email: true,
                sms: false,
                wechat: false,
            },
            adminEmail: 'notifications@example.com',
            priorityLevel: 'realtime',
        };
        await NotificationSetting.create(notificationSettingData);
        console.log('NotificationSetting data seeded.');
        return await NotificationSetting.findOne();
    } catch (error) {
        console.error('Error seeding notification settings:', error);
        throw error;
    }
}


// --- BackupSetting Data ---
async function seedBackupSettings() {
    try {
        const backupSettingData = {
            autoBackup: true,
            frequency: 'daily',
            retentionCount: 7,
            backupTime: '03:00',
            storageLocation: 'local',
        };
        await BackupSetting.create(backupSettingData);
        console.log('BackupSetting data seeded.');
        return await BackupSetting.findOne();
    } catch (error) {
        console.error('Error seeding backup settings:', error);
        throw error;
    }
}

// --- Backup Data (Example) ---
async function seedBackups() {
    try {
        const backupsData = [];
        for(let i=0; i < 3; i++) {
            const date = getRandomDate(new Date(2023, 9, 1), new Date(2023, 11, 1));
            backupsData.push({
                date: date,
                type: i % 2 === 0 ? 'auto' : 'manual',
                fileSize: getRandomNumber(1024 * 10, 1024 * 100),
                status: 'success',
                filePath: `/backups/${date.toISOString().split('T')[0]}_backup.zip`,
            });
        }
        await Backup.insertMany(backupsData);
        console.log('Backup data seeded.');
        return await Backup.find();
    } catch (error) {
        console.error('Error seeding backups:', error);
        throw error;
    }
}

// --- UserActivityLog Data (Example) ---
async function seedUserActivityLogs(users, admins) {
    if (!users || users.length === 0) { console.error('No users for activity logs.'); return []; }
    if (!admins || admins.length === 0) { console.error('No admins for activity logs.'); return []; }
    
    try {
        const logsData = [];
        const modules = ['user', 'food', 'recipe', 'dietRecord', 'system'];
        const actions = ['login', 'view', 'create', 'update', 'delete', 'search'];
        const allActors = [...users, ...admins];

        for(let i = 0; i < 500; i++) {
            const actor = getRandomItem(allActors);
            const module = getRandomItem(modules);
            const action = getRandomItem(actions);
            logsData.push({
                userId: actor._id,
                userType: actor.username ? 'admin' : 'user',
                actionType: action,
                module: module,
                details: {
                    description: `User ${actor.name || actor.username} performed ${action} on ${module}`,
                    object: Math.random() < 0.5 ? new mongoose.Types.ObjectId().toHexString() : null,
                    ipAddress: `192.168.1.${getRandomNumber(2, 254)}`,
                    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
                },
                status: Math.random() < 0.95 ? 'success' : 'failed',
                createdAt: getRandomDate(new Date(2023, 10, 1), new Date())
            });
        }
        await UserActivityLog.insertMany(logsData);
        console.log('UserActivityLog data seeded.');
        return await UserActivityLog.find();
    } catch (error) {
        console.error('Error seeding user activity logs:', error);
        throw error;
    }
}

// --- SearchHistory Data (Example for users) ---
async function seedSearchHistories(users) {
    if (!users || users.length === 0) { console.error('No users for search histories.'); return []; }
    try {
        const searchHistoriesData = [];
        const keywords = ['鸡胸肉', '沙拉', '减肥', '早餐', '苹果派', '牛肉做法', '低卡路里', '增肌食谱'];
        const searchTypes = ['food', 'recipe'];

        for (const user of users) {
            for (let i = 0; i < getRandomNumber(5, 20); i++) {
                searchHistoriesData.push({
                    userId: user._id,
                    keyword: getRandomItem(keywords),
                    searchType: getRandomItem(searchTypes),
                    createdAt: getRandomDate(new Date(2023, 10, 1), new Date())
                });
            }
        }
        await SearchHistory.insertMany(searchHistoriesData);
        console.log('SearchHistory data seeded.');
        return await SearchHistory.find();
    } catch (error) {
        console.error('Error seeding search histories:', error);
        throw error;
    }
}


async function seedAll() {
    await connectDB();
    await clearDatabase(); // Warning: This will delete all existing data!

    // Seed data in an order that respects dependencies
    const seededAdmins = await seedAdmins();
    const seededUsers = await seedUsers();
    
    const seededFoodCategories = await seedFoodCategories();
    const seededFoods = await seedFoods(seededFoodCategories);
    
    const seededRecipeCategories = await seedRecipeCategories();
    await seedRecipes(seededRecipeCategories, seededFoods, seededAdmins);
    
    await seedDietRecords(seededUsers, seededFoods);
    await seedNutritionGoals(seededUsers);
    await seedNutritionSuggestions(seededUsers, seededFoods);
    
    await seedTags();
    await seedRoles();
    
    await seedSystemSettings();
    await seedNotificationSettings();
    await seedBackupSettings();
    await seedBackups();
    
    await seedUserActivityLogs(seededUsers, seededAdmins);
    await seedSearchHistories(seededUsers);

    console.log('Database seeding completed!');
    await mongoose.disconnect();
    console.log('MongoDB disconnected.');
}

seedAll().catch(error => {
    console.error('Seeding failed:', error);
    mongoose.disconnect();
    process.exit(1);
});

// To run this script: node scripts/seedDb.js
// Ensure you have .env file in the root with MONGODB_URI or update the MONGODB_URI constant.
// Ensure all model paths are correct relative to this script file. 